<script setup>
	import {
		ref,
		computed,
		nextTick
	} from 'vue';
	import {
		cancelOrderApi,
		changeOrderApi,
		reserveOrderApi
	} from '@/api/order'
	import {
		imgUrl,
		miniPay
	} from "../../../utils/global";
	import {
		proCityList
	} from '../../../utils/city';
	import {
		useOrderStore
	} from '@/store/order';
	import {
		addReserveApi,
		upPaymentStatus,
		wxPayApi,
		wxRefundApi
	} from '@/api/reserve';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		getOrganizationListApi,
		getHospitalByPackage,
		createReservation,
		mNchangeReservationApi,
		getphlist,
		pHaddcheckinfoApi,
		pHsetcheckApi,
		pHeditcheckinfoApi,
		rCqueryCapacity,
		mNgetSchedule
	} from '@/api/case';
	import {
		getDistanceApi,
		getLocationApi
	} from '@/api/global';
	import moment from "moment";
	// import NiceuiCityPickerView from 'uni_modules/niceui-city-picker-view.vue'  //路径根据导入后的真实路径为准
	const isChange = ref(false);
	const orderStore = useOrderStore();
	import {
		useUserStore
	} from '@/store/user';

	const userStore = useUserStore();
	const location = ref({
		lat: 0,
		lng: 0
	});
	const picker = ref()
	const area = ref(null)
	const date_time = ref(null)
	const getMultipleMonths = () => {
		let days = []
		const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
		// 获取今天的日期
		const today = moment();
		// 获取今天开始两个月后的日期
		const twoMonthsFromNow = today.clone().add(2, 'months');
		const range = [];
		for (let m = moment(today); m.isBefore(twoMonthsFromNow); m.add(1, 'days')) {
			range.push(m.clone());
		}
		range.forEach(date => {
			days.push({
				day: weekdays[date.weekday()],
				date: date.format('MM/DD'),
				fullDate: date.format('YYYY-MM-DD')
			})

		});
		return days
	}
	// 普惠列表
	const getphList = () => {
		getphlist().then(res => {
			res.forEach(item => {
				item["storeName"] = item.storename
				item["storeAddress"] = item.address
				item["tags"] = ['绿通服务', '自助登记']
				item["cityName"] = item.address
				item["openingHours"] = item.examination_hours
			})
			organizationList.value = res
		})
	}
	// 美年接口
	const getMnHospital = () => {
		console.log()
		getHospitalByPackage({
			packageid: orderStore.selectedPackage.packageid,
			// packageid:"00AY6ZZLI35CY"
		}).then(res => {
			res.forEach(item => {
				item["storeName"] = item.supplierName
				item["storeAddress"] = item.hospitalName
				item["tags"] = ['绿通服务', '自助登记']
				item["cityName"] = item.city + item.address
				item["openingHours"] = ""
			})
			organizationList.value = res
		})
	}
	// 瑞慈接口
	const getRcHospital = async () => {
		try {

			const _location = await getLocationApi();
			location.value = {
				lat: _location.location.lat,
				lng: _location.location.lng
			};
			const results = await getOrganizationListApi();


			const distance = await getDistanceApi({
				from: `${location.value.lat},${location.value.lng}`,
				to: results.map(item => {
					return `${item.latitude},${item.longitude}`
				}).join(';')
			});
			let elements = []
			// 先找出最小距离
			organizationList.value = []
			if (filter_list.value.includes(orderStore.selectedPackage.packageid + '')) {
				results.forEach((item, index) => {
					if (item.storeName.includes("幸元会")) {
						elements.push(distance.rows[0].elements[index])
						organizationList.value.push({
							...item,
							tags: ['绿通服务', '自助登记']
						})
					}

				})
			} else {
				elements = distance.rows[0].elements
				organizationList.value = results.map((item, index) => {
					return {
						...item,
						tags: ['绿通服务', '自助登记']
					}
				});
			}

			const minDist = Math.min(...elements.map(item => item.distance));
			elements.forEach((item, index) => {
				const dist = item.distance;
				// 设置距离显示
				organizationList.value[index].distance = dist >= 1000 ?
					`${(dist / 1000).toFixed(1)}km` :
					`${dist}m`;

				// 如果是最小距离，添加标签
				if (dist === minDist) {
					organizationList.value[index].tags = ['距离最近', ...organizationList.value[index]
						.tags
					];
				}
			});

		} catch (error) {
			console.log(error)
			uni.showToast({
				title: '获取机构信息失败',
				icon: 'none'
			});
		}
	}

	const dateList = ref(getMultipleMonths());
	const currentDate = ref(0);
	const calendar_show = ref(false)
	const organizationList = ref([]);

	// 计算总价
	const totalPrice = computed(() => {
		let total = orderStore.selectedPackage?.price || 0;
		// total += orderStore.selectedAddons.reduce((sum, addon) => sum + addon.price, 0);
		return total;
	});

	const columns = ref(
		[
			['全部'],
			["全部"]
		]
	)
	// 当前省下标
	const province = ref(0)
	// 当前市下标
	const market = ref(0)
	const filter_list = ref(['2560839101', '2560839102', '2560839103', '2560839104', '2560839105', '2560839106'])
	onLoad(async (options) => {
		await nextTick();
		console.log(orderStore.selectedPackage.packageid_copy, "packageid_copy")
		console.log(orderStore.selectedPackage.packageid, "packageid")
		// 设置省的数据
		proCityList.forEach(item => {
			columns.value[0].push(item.name)
		})
		if (typeof options.type !== 'undefined' && Number(options.type) === 1) {
			if (orderStore.order.status !== 2) {
				uni.showToast({
					title: '当前订单状态无法改约',
					icon: 'error'
				});
				return;
			}
			isChange.value = true;
		} else {
			isChange.value = false;
		}
		// 美年
		if (orderStore.customerInfo.brand_list.includes("2")) {
			getMnHospital()
			return
		}
		// 瑞慈
		if (orderStore.customerInfo.brand_list.includes("1")) {
			getRcHospital()
			return
		}
		// 惠普
		if (orderStore.customerInfo.brand_list.includes("3")) {
			getphList()
			return
		}
	});
	const inventory_loading = ref(false)
	// 选择机构
	const selectOrganization = (org) => {
		date_time.value = null
		// 取消其他机构的选择
		organizationList.value.forEach(item => {
			item.isSelected = false;
			item.selectedTimeSlot = '';
		});
		// 选择当前机构
		org.isSelected = true;
		if (orderStore.customerInfo.brand_list.includes("2")) {
			inventory_loading.value = true
			mNgetInventory(org)
			return
		}
		if (orderStore.customerInfo.brand_list.includes("1")) {
			inventory_loading.value = true
			rCgetInventory(org)
			return
		}
		if (orderStore.customerInfo.brand_list.includes("3")) {
			// inventory_loading.value = true
			pHgetInventory(org)
			return
		}

	};
	const max_date = ref(0)
	const min_date = ref(0)
	const calendar_list = ref([])
	const formatter = (day) => {
		if (orderStore.customerInfo.brand_list.includes("3")) {
			return day
		}
		let time = moment(day.date).format('YYYY-MM-DD')
		let info = calendar_list.value.find(item => moment(day.date).format('YYYY-MM-DD') == moment(item.scheduleDate)
			.format('YYYY-MM-DD'))
		if (info) {
			let text = ""
			// 美年只显示可预约 不可预约
			if (orderStore.customerInfo.brand_list.includes("2")) {
				text = info.personCount > 0 ? '可预约' : `不可预约`
			} else {
				text = info.personCount > 10 ? '可预约' : `仅余${info.personCount}`
			}
			day.bottomInfo = text
			if (info.personCount == 0) {
				day.bottomInfo = `不可预约`
				day.disabled = true
			}
		} else {
			day.disabled = true
			day.bottomInfo = `不可预约`
		}
		return day
	}
	const createFail = ref(false)
	const cancelLoading = ref(false)
	const bookingno = ref("")
	const refundClick = () => {
		if (bookingno.value == "") {
			uni.showToast({
				title: "缺少bookingno",
				icon: "none"
			})
			return
		}
		if (cancelLoading.value) {
			uni.showToast({
				title: "处理中",
				icon: "none"
			})
			return
		}
		if (orderStore.selectedPackage?.price > 0) {
			wxRefundApi({
				bookingno: bookingno.value,
				price: orderStore.selectedPackage?.price
			}).then(res => {
				cancelLoading.value = false
				uni.showToast({
					title: '退款成功',
					icon: 'none'
				});
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/reserve/index/index'
					});
				}, 1000);
			}).catch(err => {
				cancelLoading.value = false
			})
		}

	}
	const pHgetInventory = () => {
		const today = moment();
		min_date.value = today.format('YYYY-MM-DD');
		max_date.value = today.clone().add(15, 'days').format('YYYY-MM-DD');
		calendar_show.value = true
	}
	const mNgetInventory = (org) => {
		mNgetSchedule({
			packageid: orderStore.selectedPackage.packageid,
			// packageid:"00AY6ZZLI35CY",
			hospitalCode: org.hospitalCode
		}).then(res => {
			const moments = res.map(date => moment(date.scheduleDate, 'YYYY-MM-DD'));
			min_date.value = moment.min(moments).format('YYYY-MM-DD');
			max_date.value = moment.max(moments).format('YYYY-MM-DD');

			calendar_list.value = res
			calendar_show.value = true
			inventory_loading.value = false
		}).catch(() => {
			inventory_loading.value = false
			org.isSelected = false
		})
	}
	const rCgetInventory = (org) => {
		console.log(org)
		rCqueryCapacity({
			packageid: orderStore.selectedPackage.packageid,
			storeid: org.storeId
		}).then(res => {
			const moments = res.map(date => moment(date.date, 'YYYY-MM-DD'));
			min_date.value = moment.min(moments).format('YYYY-MM-DD');
			max_date.value = moment.max(moments).format('YYYY-MM-DD');
			calendar_list.value = []
			res.forEach(item => {
				calendar_list.value.push({
					...item,
					scheduleDate: item.date,
					personCount: item.capacity
				})
			})
			console.log(calendar_list.value)
			calendar_show.value = true
			inventory_loading.value = false
		}).catch(() => {
			inventory_loading.value = false
			org.isSelected = false
		})
	}
	const selectTimeSlot = (org, timeSlot) => {
		if (org.isSelected) {
			org.selectedTimeSlot = timeSlot;
		}
	};
	const columnChange = (e) => {
		let {
			column,
			value
		} = e.detail
		if (column == 0) {
			if (value == 0) {
				columns.value[1] = ["全部"]
				market.value = 0
				return
			}
			let province = columns.value[0][value]
			let temp = proCityList.find(item => item.name == province)
			if (temp) {
				columns.value[1] = ["全部"]
				market.value = 0
				temp.children.forEach(item => {
					columns.value[1].push(item.name)
				})
			}
		}
	}
	const bindPickerChange = (e) => {
		let {
			value
		} = e.detail
		province.value = value[0]
		market.value = value[1]
		organizationList.value.forEach(item => {
			item.isSelected = false;
			item.selectedTimeSlot = '';
		});
	}
	const org_list = computed(() => {
		if (province.value == 0 && market.value == 0) {
			return organizationList.value
		}
		let cityName = ""
		if (province.value != 0 && market.value == 0) {
			cityName = columns.value[0][province.value]
		}
		if (province.value != 0 && market.value != 0) {
			cityName = columns.value[1][market.value]
		}
		let list = []
		organizationList.value.forEach(item => {
			if (item.cityName.includes(cityName)) {
				list.push(item)
			}
		})
		return list
	})
	const index = ref(0)
	const continueNext = async () => {
		if (orderStore.customerInfo.brand_list.includes("2")) {
			mNContinueNext()
			return
		}
		if (orderStore.customerInfo.brand_list.includes("1")) {
			rContinueNext()
			return
		}
		if (orderStore.customerInfo.brand_list.includes("3")) {
			pHContinueNext()
			return
		}
	};
	const calendarConfirm = (e) => {
		date_time.value = moment(e[0]).format('YYYY-MM-DD')
		calendar_show.value = false
		// console.log(e[0],date_time.value)
	}
	const calendarClose = (e) => {
		calendar_show.value = false
	}
	const changePaymentStatus = () => {
		upPaymentStatus({
			reserveno: orderStore.order.reserveNo,
		}).then(() => {
			uni.hideLoading()
			// uni.reLaunch({
			uni.redirectTo({
				url: '/pages/case/info/index?id=' + orderStore.customerInfo.id
			});
		}).catch(() => {
			uni.hideLoading()
			// uni.reLaunch({
			uni.redirectTo({
				url: '/pages/case/info/index?id=' + orderStore.customerInfo.id
			});
		})
	}
	const pHContinueNext = () => {
		if (!date_time.value) {
			uni.showToast({
				title: '请选择时间段',
				icon: 'none'
			});
			return;
		}
		const info = organizationList.value.find(org => org.isSelected);
		if (!info) {
			uni.showToast({
				title: '请选择机构和时间段',
				icon: 'none'
			});
			return;
		}
		// status ，1预约，2取消，3改约
		if (isChange.value) {
			// 改约
			pHeditcheckinfoApi({
				id: orderStore.customerInfo.id,
				examDate: date_time.value,
				storename: info.storename,
				storeid: info.storeid,
			}).then(res => {
				pHsetcheckApi({
					id: orderStore.customerInfo.id,
					status: 3,
					storeid: info.storeid,
					storename: info.storename,
					examDate: date_time.value,
				}).then(() => {
					uni.hideLoading()
					uni.showToast({
						title: res,
						icon: 'none',
						duration: 900
					});
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/reserve/index/index'
						});
					}, 1000);
				})
			})
		} else {
			addReserveApi({
				id: orderStore.customerInfo.id,
				uid: userStore.userInfo.id,
				examDate: date_time.value,
				examTime: orderStore.selectedOrganization.examTime
			}).then((res) => {
				bookingno.value = res
				if (orderStore.selectedPackage?.price > 0) {
					wxPayApi({
						bookingno: res,
						price: orderStore.selectedPackage?.price,
						uid: userStore.userInfo.id,
					}).then(pay_res => {
						miniPay(pay_res).then(result => {
							pHcreate(info)
						}).catch(err => {})
					})
				} else {
					pHcreate(info)
				}

			})
		}
	}
	const pHcreate = (info) => {
		pHaddcheckinfoApi({
			id: orderStore.customerInfo.id,
			examDate: date_time.value,
			packagename: orderStore.selectedPackage.title,
			storename: info.storename,
			packageid: orderStore.selectedPackage.packageid,
			storeid: info.storeid,
		}).then(async res => {
			pHsetcheckApi({
				id: orderStore.customerInfo.id,
				status: 1,
				storeid: info.storeid,
				storename: info.storename,
				examDate: date_time.value,
			}).then(() => {
				uni.hideLoading()
				uni.showToast({
					title: res,
					icon: 'none',
					duration: 900
				});
				// uni.reLaunch({
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/case/info/index?id=' +
							orderStore
							.customerInfo.id
					});
				}, 1000)

				createFail.value = false
			}).catch(err => {
				if (orderStore.selectedPackage?.price > 0) {
					createFail.value = true
				}
			})
		}).catch((err) => {
			if (orderStore.selectedPackage?.price > 0) {
				createFail.value = true
			}
			uni.hideLoading()
			uni.showModal({
				content: err.message,
				showCancel: false
			})
		})
	}
	const mNContinueNext = () => {
		if (!date_time.value) {
			uni.showToast({
				title: '请选择时间段',
				icon: 'none'
			});
			return;
		}
		const info = organizationList.value.find(org => org.isSelected);
		if (isChange.value) {
			// 改约
			mNchangeReservationApi({
				hospitalCode: info.hospitalCode,
				examDate: date_time.value,
				hospitalName: info.hospitalName,
				id: orderStore.customerInfo.id
			}).then(res => {
				uni.hideLoading()
				uni.showToast({
					title: '改约成功',
					icon: 'none',
					duration: 1000
				});
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/reserve/index/index'
					});
				}, 1000);
			})
		} else {
			addReserveApi({
				id: orderStore.customerInfo.id,
				uid: userStore.userInfo.id,
				examDate: orderStore.selectedOrganization.examDate,
				examTime: orderStore.selectedOrganization.examTime
			}).then((res) => {
				bookingno.value = res
				if (orderStore.selectedPackage?.price > 0) {
					wxPayApi({
						bookingno: res,
						price: orderStore.selectedPackage?.price,
						uid: userStore.userInfo.id,
					}).then(pay_res => {
						miniPay(pay_res).then(result => {
							mNCreate(info)
						}).catch(err => {})
					})
				} else {
					mNCreate(info)
				}

			})
		}
	}
	const mNCreate = (info) => {
		createReservation({
			hospitalCode: info.hospitalCode,
			examDate: date_time.value,
			hospitalName: info.hospitalName,
			id: orderStore.customerInfo.id,
			packageid: orderStore.selectedPackage.packageid
		}).then(() => {
			createFail.value = false
			uni.hideLoading()
			uni.showToast({
				title: "预约成功",
				icon: "none"
			})
			setTimeout(() => {
				// uni.reLaunch({
				uni.redirectTo({
					url: '/pages/case/info/index?id=' +
						orderStore.customerInfo.id
				});
			}, 1000)

		}).catch(err => {
			if (orderStore.selectedPackage?.price > 0) {
				createFail.value = true
			}
		})
	}
	const rContinueNext = async () => {
		if (!date_time.value) {
			uni.showToast({
				title: '请选择时间段',
				icon: 'none'
			});
			return;
		}
		const selectedOrg = organizationList.value.find(org => org.isSelected);
		console.log(selectedOrg, "selectedOrg")
		if (!selectedOrg) {
			uni.showToast({
				title: '请选择机构和时间段',
				icon: 'none'
			});
			return;
		}
		uni.showLoading({
			title: "确认信息中..."
		})
		try {
			orderStore.setOrganization({
				name: selectedOrg.storeName,
				address: selectedOrg.storeAddress,
				storeId: Number(selectedOrg.storeId),
				examDate: date_time.value,
				examTime: selectedOrg.openingHours,
			});

			try {
				if (isChange.value) {
					changeOrderApi({
						bookingno: orderStore.order.bookingno,
						reserveNo: orderStore.order.reserveNo,
						examDate: orderStore.selectedOrganization.examDate,
						packageId: orderStore.selectedPackage.packageid,
						storeId: orderStore.selectedOrganization.storeId,
						storeName: orderStore.selectedOrganization.name,
						examTime: orderStore.selectedOrganization.examTime
					}).then(res => {
						uni.showToast({
							title: '改约成功',
							icon: 'none',
							duration: 1000
						});
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/reserve/index/index'
							});
						}, 1000);
					})
					return
				}
				addReserveApi({
					id: orderStore.customerInfo.id,
					uid: userStore.userInfo.id,
					examDate: orderStore.selectedOrganization.examDate,
					examTime: orderStore.selectedOrganization.examTime
				}).then((res) => {
					bookingno.value = res
					if (orderStore.selectedPackage?.price > 0) {
						wxPayApi({
							bookingno: res,
							price: orderStore.selectedPackage?.price,
							uid: userStore.userInfo.id,
						}).then(pay_res => {
							miniPay(pay_res).then(result => {
								rCcreate(res)
							}).catch(err => {})
						})
					} else {
						rCcreate(res)
					}
				}).catch((err) => {})
			} catch (error) {
				uni.hideLoading()
			}
		} catch (error) {
			uni.hideToast();
			uni.showToast({
				title: '保存失败',
				icon: 'error'
			});
		}
	}
	const rCcreate = (bookingno) => {
		reserveOrderApi({
			id: orderStore.customerInfo.id,
			storeName: orderStore.selectedOrganization.name,
			storeId: orderStore.selectedOrganization.storeId,
			additionsId: orderStore.selectedAddons.map(
				item => {
					return item.additionsid
				}),
			packageId: orderStore.selectedPackage.packageid,
			examDate: orderStore.selectedOrganization.examDate,
			examTime: orderStore.selectedOrganization.examTime
		}).then(() => {
			createFail.value = false
			uni.hideLoading()
			uni.showToast({
				title: "预约成功",
				icon: "none"
			})
			setTimeout(() => {
				// redirectTo
				// uni.reLaunch({
				uni.redirectTo({
					url: '/pages/case/info/index?id=' +
						orderStore.customerInfo.id
				});
			}, 1000)

		}).catch(err => {
			if (orderStore.selectedPackage?.price > 0) {
				createFail.value = true
			}
		})
	}
</script>

<template>
	<view class="app-orgnization">
		<up-calendar :minDate="min_date" :formatter="formatter" :maxDate="max_date" :show="calendar_show"
			@close="calendarClose" @confirm="calendarConfirm"></up-calendar>
		<view class="date-wrapper">
			<view class="date-header"
				style="background: linear-gradient(180deg, #ff7f36 0%, #f54730 100%);padding:10rpx 20rpx;border-radius: 14rpx;">
				<text style="color:#fff;font-size: 28rpx;">请选择地区</text>
				<view class="header-right" style="flex:1;">
					<picker ref="picker" style="flex:1;" mode="multiSelector" @change="bindPickerChange"
						@columnchange="columnChange" :value="[province,market]" :range="columns">
						<view class="" style="flex:1;display: flex;justify-content: flex-end;">
							<text class="picker-text" style="color:#fff">{{columns[0][province]}}</text>
							<text style="color:#fff" class="picker-text"
								v-if="columns[1][market]!=columns[0][province]&&columns[1][market]!='全部'">-{{columns[1][market]}}</text>
							<!-- <uni-icons type="right" size="12" color="#b6b6b8"></uni-icons> -->
						</view>

					</picker>
				</view>
			</view>
			<!-- 	<view class="date-content">
				<view class="date-item" v-for="(item, index) in dateList" :key="index"
					:class="currentDate === index ? 'date-item-active' : ''" @click="currentDate = index">
					<text>{{ item.day }}</text>
					<text>{{ item.date }}</text>
				</view>
			</view> -->
		</view>

		<view class="org-list">
			<view v-for="(org, index) in org_list" :key="index" class="org-item"
				:class="org.isSelected ? 'org-item-active' : ''">
				<view class="item-row">
					<text class="item-title">{{ org.storeName }}</text>
					<text class="item-dist">{{ org.distance }}</text>
				</view>
				<text class="item-address">{{ org.storeAddress }}</text>
				<view class="item-row">
					<view class="tag-wrapper">
						<view style="font-size: 28rpx;" v-if="date_time&&org.isSelected">当前选择:{{date_time}}</view>

						<!-- <text v-for="(tag, index) in org.tags" :key="index" class="tag-item"
							:class="index === 0 ? 'tag-item-active' : ''">
							{{ tag }}
						</text> -->
					</view>
					<view class="item-button" :class="org.isSelected ? 'item-button-active' : ''"
						@click="selectOrganization(org)">
						<!-- {{ org.isSelected ? '已选择' : '选择' }} -->
						{{org.isSelected&&inventory_loading?"处理中...":'选择'}}
					</view>
				</view>
				<!-- 	<view class="date-row" v-if="org.openingHours">
					<text class="date-item" :class="org.selectedTimeSlot === org.openingHours ? 'date-item-active' : ''"
						@click="selectTimeSlot(org, org.openingHours)">{{ org.openingHours }}</text>
				</view> -->
			</view>
			<view style="color: #b6b6b8;
                    font-weight: 400;height:200rpx;
                    font-size: 26rpx;display: flex;align-items: center;justify-content: center;"
				v-if="org_list.length==0">
				暂无数据
			</view>
		</view>

		<view class="bottom-wrapper">
			<view class="bottom-row">
				<text>
					合计：
					<text class="price-text">￥{{ totalPrice }}</text>
				</text>

				<text>
					套餐+已加{{ orderStore.selectedAddons.length }}项
				</text>
			</view>
			<!-- <view class="bottom-button" v-if="createFail" @click="refundClick">去退款</view> -->
			<view class="bottom-button" @click="continueNext">下一步</view>
		</view>
	</view>
</template>

<style src="./style.scss" scoped />